Hoisting


Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (to the top of the current script or the current function) before code execution. This means that you can use functions and variables before they are declared.

Variable Hoisting

Variables declared with var are hoisted to the top of their scope and initialized with undefined. Variables declared with let and const are also hoisted but not initialized.

console.log(foo); // undefined
var foo = 'foo';

console.log(bar); // ReferenceError: Cannot access 'bar' before initialization
let bar = 'bar';

Function Hoisting

Function declarations are hoisted to the top of their scope, allowing you to call the function before its declaration.

console.log(myFunction()); // "Hello, World!"

function myFunction() {
    return "Hello, World!";
}

Class Hoisting

Classes are hoisted but not initialized. This means you cannot use a class before it is declared.

const myInstance = new MyClass(); // ReferenceError: Cannot access 'MyClass' before initialization

class MyClass {
    constructor() {
        this.name = "MyClass";
    }
}

Examples

Here are some examples demonstrating hoisting in JavaScript:

console.log(a); // undefined
var a = 10;

console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;

console.log(c); // ReferenceError: Cannot access 'c' before initialization
const c = 30;

console.log(myFunc()); // "Hello from myFunc"
function myFunc() {
    return "Hello from myFunc";
}

const myInstance = new MyClass(); // ReferenceError: Cannot access 'MyClass' before initialization
class MyClass {
    constructor() {
        this.name = "MyClass";
    }
}

For more detailed information, you can check out resources like W3Schools and MDN Web Docs.